<!-- views/counselor/HolidayPublish.vue -->
<template>
  <div class="holiday-publish">
    <!-- 操作工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon> 新增假期
      </el-button>
      <el-button @click="loadHolidays">
        <el-icon><Refresh /></el-icon> 刷新
      </el-button>
    </div>

    <!-- 假期列表 -->
    <el-table :data="holidays" border class="holiday-table">
      <el-table-column prop="name" label="假期名称" width="180" />

      <el-table-column label="放假时间" width="220">
        <template #default="{ row }">
          {{ $formatDate(new Date(row.startDate), 'yyyy-MM-dd') }} 至
          {{ $formatDate(new Date(row.endDate), 'yyyy-MM-dd') }}
        </template>
      </el-table-column>

      <el-table-column label="登记时间" width="280">
        <template #default="{ row }">
          {{ $formatDate(new Date(row.registerStart), 'yyyy-MM-dd HH:mm') }} 至
          {{ $formatDate(new Date(row.registerEnd), 'yyyy-MM-dd HH:mm') }}
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag v-if="row.status === 0" type="info">待发布</el-tag>
          <el-tag v-else-if="row.status === 1" type="warning">进行中</el-tag>
          <el-tag v-else type="success">已完成</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button
              size="small"
              type="primary"
              @click="editHoliday(row)"
              :disabled="row.status !== 0"
          >
            修改
          </el-button>
          <el-button
              size="small"
              type="success"
              @click="publishHoliday(row.id)"
              :disabled="row.status !== 0"
          >
            发布
          </el-button>
          <el-button
              size="small"
              @click="viewRecords(row.id)"
          >
            查看登记
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="pagination"
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
        :title="isEdit ? '编辑假期' : '新增假期'"
        v-model="dialogVisible"
        width="500px"
    >
      <el-form :model="holidayForm" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="假期名称" prop="name">
          <el-select v-model="holidayForm.name" placeholder="请选择" style="width: 100%">
            <el-option
                v-for="item in holidayNames"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="放假开始" prop="startDate">
          <el-date-picker
              v-model="holidayForm.startDate"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="放假结束" prop="endDate">
          <el-date-picker
              v-model="holidayForm.endDate"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="登记开始" prop="registerStart">
          <el-date-picker
              v-model="holidayForm.registerStart"
              type="datetime"
              placeholder="选择日期时间"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="登记截止" prop="registerEnd">
          <el-date-picker
              v-model="holidayForm.registerEnd"
              type="datetime"
              placeholder="选择日期时间"
              style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveHoliday">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      holidays: [],

      // 假期名称选项
      holidayNames: ['五一劳动节', '端午节', '国庆节', '寒假', '春节', '清明节', '中秋节'],

      // 对话框相关
      dialogVisible: false,
      isEdit: false,
      holidayForm: {
        id: null,
        name: '',
        startDate: '',
        endDate: '',
        registerStart: '',
        registerEnd: ''
      },
      formRules: {
        name: [{ required: true, message: '请选择假期名称', trigger: 'change' }],
        startDate: [{ required: true, message: '请选择放假开始时间', trigger: 'change' }],
        endDate: [{ required: true, message: '请选择放假结束时间', trigger: 'change' }],
        registerStart: [{ required: true, message: '请选择登记开始时间', trigger: 'change' }],
        registerEnd: [{ required: true, message: '请选择登记截止时间', trigger: 'change' }]
      }
    };
  },
  async mounted() {
    await this.loadHolidays();
  },
  methods: {
    /**
     * 加载假期列表
     */
    async loadHolidays(pageNum = 1) {
      try {
        const res = await $counselorAPI.getHolidays(pageNum, this.pageSize);
        this.holidays = res.records || [];
        this.total = res.total || 0;
        this.currentPage = pageNum;
      } catch (err) {
        console.error('加载假期失败', err);
        this.$message.error('加载假期列表失败');
      }
    },

    /**
     * 显示新增对话框
     */
    showAddDialog() {
      this.holidayForm = {
        id: null,
        name: '',
        startDate: '',
        endDate: '',
        registerStart: '',
        registerEnd: ''
      };
      this.isEdit = false;
      this.dialogVisible = true;
    },

    /**
     * 编辑假期
     *
     * @param holiday - 假期对象
     */
    editHoliday(holiday) {
      this.holidayForm = {
        id: holiday.id,
        name: holiday.name,
        startDate: new Date(holiday.startDate),
        endDate: new Date(holiday.endDate),
        registerStart: new Date(holiday.registerStart),
        registerEnd: new Date(holiday.registerEnd)
      };
      this.isEdit = true;
      this.dialogVisible = true;
    },

    /**
     * 保存假期
     */
    async saveHoliday() {
      try {
        // 表单验证
        await this.$refs.formRef.validate();

        // 调用API
        if (this.isEdit && this.holidayForm.id) {
          // 更新假期
          this.$message.success('假期修改成功');
        } else {
          // 发布假期
          await $counselorAPI.publishHoliday({
            name: this.holidayForm.name,
            startDate: this.holidayForm.startDate,
            endDate: this.holidayForm.endDate,
            registerStart: this.holidayForm.registerStart,
            registerEnd: this.holidayForm.registerEnd
          });
          this.$message.success('假期发布成功');
        }

        // 关闭对话框，刷新列表
        this.dialogVisible = false;
        await this.loadHolidays(this.currentPage);
      } catch (err) {
        console.error('保存假期失败', err);
        this.$message.error('保存假期失败，请重试');
      }
    },

    /**
     * 查看登记记录
     *
     * @param id - 假期ID
     */
    viewRecords(id) {
      // 跳转到统计报表页面
      this.$router.push(`/counselor/report?holidayId=${id}`);
    },

    /**
     * 分页切换
     *
     * @param pageNum - 页码
     */
    handlePageChange(pageNum) {
      this.loadHolidays(pageNum);
    }
  }
};
</script>